import React, { useEffect, useState } from "react";
import MyNavBar from "@/components/MyNavBar.jsx";
import MyButton from "@/components/MyButton.jsx";
import { Form, Input, Button, Toast } from "antd-mobile";
import Api from "@/api";
import { connect } from "react-redux";
import action from "@/store/action";
import "./Login.scss";

const validate = {
  phone(_, value) {
    value = value.trim();
    let reg =
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    if (value.length === 0) return Promise.reject(new Error("手机号必填"));
    if (!reg.test(value)) return Promise.reject(new Error("手机号格式不正确"));
    return Promise.resolve();
  },
  code(_, value) {
    value = value.trim();
    let reg = /^\d{6}$/;
    if (value.length === 0) return Promise.reject(new Error("验证码必填"));
    if (!reg.test(value)) return Promise.reject(new Error("验证码6位数字"));
    return Promise.resolve();
  },
};

function Login() {
  // 表单实例状态
  const [formIns] = Form.useForm();

  const [disabled, setDisabled] = useState(false),
    [sendText, setSendText] = useState("发送验证码");

  // 表单提交
  const submit = async () => {
    // 此时表单校验已经成功。values：Form表单组件自动收集的每个表单中的信息
    try {
      await formIns.validateFields(); // 表单校验
      let { phone, code } = formIns.getFieldsValue();
      const res = await Api.login(phone, code);
      if (+res.code !== 0) {
        Toast.show({
          icon: "fail",
          content: "登陆失败",
        });
        formIns.resetFields(["code"]); // 重置验证码
      } else {
      }
    } catch (error) {
      console.log(error);
    }
  };

  // 点击发送验证码按钮
  let timer = null,
    num = 30;
  const countDown = () => {
    num--;
    if (num < 1) {
      clearInterval(timer);
      timer = null;
      setSendText(`发送验证码`);
      setDisabled(false);
      return;
    }
    setSendText(`${num}秒后重发`);
  };
  const sendCode = async () => {
    try {
      await formIns.validateFields(["phone"]); // 表单校验
      const res = await Api.phoneCode(formIns.getFieldValue("phone"));
      console.log(res);
      setDisabled(true);

      Toast.show({
        icon: "success",
        content: "验证码已发送",
      });
      setSendText(`${num}秒后重发`);
      if (!timer) timer = clearInterval(() => countDown, 1000);
    } catch (error) {
      console.log(error);
    }
  };
  // 组件销毁时清除定时器
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer);
        timer = null;
      }
    };
  }, []);

  return (
    <>
      <MyNavBar />
      <div className="login-box">
        <Form
          layout="horizontal"
          form={formIns}
          initialValues={{ phone: "", code: "" }}
          footer={
            <MyButton type="submit" color="primary" onClick={submit}>
              提交
            </MyButton>
          }
        >
          <Form.Item
            name="phone"
            label="手机号"
            rules={[{ validator: validate.phone }]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
          {/* rules={[{ validator: validate.code }]} */}
          <Form.Item
            label="验证码"
            name="code"
            rules={[
              { required: true, message: "验证码必填" },
              { pattern: /^\d{6}$/, message: "验证码6位数字" },
            ]}
            extra={
              <MyButton
                color="primary"
                disabled={disabled}
                size="small"
                onClick={sendCode}
              >
                {sendText}
              </MyButton>
            }
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>
        </Form>
      </div>
    </>
  );
}

export default connect(null, action.base)(Login);
